package com.helloniu.fl.widget {

import mx.containers.Canvas;
import mx.core.Container;
import mx.core.UIComponent;

public class ZoomableContainer {
	private var childArr:Array = new Array();
	
	public function ZoomableContainer() {
		super();
	}
	
	/**
	 * Add the component to the container.
	 * @comp the component tobe added.
	 * @idx the component layer index. 
	 */ 
	public function addLayerChild(comp:UIComponent, idx:Number = 0):void {
	    childArr[idx] = comp;
	
		initLayerChild(comp);
	
	    addChildAt(comp, idx);
	}

	private function initLayerChild(comp:UIComponent):void {
		comp.x = 0;
		comp.y = 0;
		
		// @temp tonyy, do not fix the size of swfloader, the size of swfloader should be fixed
		// by the loader content
		//comp.width = this.unscaledWidth;
		//comp.height = this.unscaledHeight;
		
		if(comp is Container) {
			(comp as Container).horizontalScrollPolicy = "off";
			(comp as Container).verticalScrollPolicy = "off";		
		}
	}
	
	/**
	 * Zoom the children of the container.
	 * @zoomNum the zoomNum should be 10~~2000, when the zoomNum is too litter to too big,
	 * the zoomNum is meaningless.
	 */	
	public function zoomEffect(zoomNum:Number):void {
		if(zoomNum < 10) {
			zoomNum = 10;
		}
		
		if(zoomNum > 2000) {
			zoomNum = 2000;
		}

		var w:Number = this.unscaledWidth;
		var h:Number = this.unscaledHeight;
	
		var nw:Number = w * zoomNum / 100;
		var nh:Number = h * zoomNum / 100;
		
		updateLayerChildrenSize(nw, nh, zoomNum);	
	}	
	
	private function updateLayerChildrenSize(w:Number, h:Number, zoomNum:Number = 100):void {
		for(var i:int = 0; i < childArr.length; i++) {
			if(childArr[i] is IZoomableComponent) {
				// @problem this zoom effect will not invoke the scroll of parent container
				// be shown				
				zoomEffect2((childArr[i] as UIComponent), zoomNum);
				continue;
			}
			
			// @by tonyy, email:yuan.yuan@gnetis.com, use width@height insteadof setActuralSize
			// to avoid some flex bugs 
			(childArr[i] as UIComponent).width = w;
			(childArr[i] as UIComponent).height =  h;	
		}
	}
	
	/**
	 * Zoom the children of the container.
	 * @zoomNum the zoomNum should be 10~~2000, when the zoomNum is too litter to too big,
	 * the zoomNum is meaningless.
	 * @problem this zoom effect the scrollbar will not be shown.
	 */	
	private function zoomEffect2(comp:UIComponent, zoomNum:Number):void {
		if(zoomNum < 10) {
			zoomNum = 10;
		}

		if(zoomNum > 2000) {
			zoomNum = 2000;
		}

		comp.scaleX = zoomNum/100;
		comp.scaleY = zoomNum/100;
		
		// @temp tonyy, force the parent to show the scroll
		// @problem, set scaleX/scaleY is an async function
		//comp.width = comp.width;
		//comp.height = comp.height;			
	}
}
}